package com.elitetyc.eliteim;

import cn.hutool.core.util.StrUtil;
import com.elitetyc.eliteim.client.command.impl.LoginInnerCommand;
import com.elitetyc.eliteim.client.config.IMClientProperties;
import com.elitetyc.eliteim.client.handler.ThreadExceptionHandler;
import com.elitetyc.eliteim.client.scanner.TerminalScanner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author yuanchao.tan
 * @version 1.0
 * @description TODO
 * @Date 2021/9/17 9:33
 */
@SpringBootApplication(scanBasePackages = "com.elitetyc.eliteim")
@Slf4j
public class EliteIMClientApplication implements CommandLineRunner {

    @Autowired
    private TerminalScanner terminalScanner;

    @Autowired
    private IMClientProperties imClientProperties;

    @Autowired
    private LoginInnerCommand loginInnerCommand;

    public static void main(String[] args) {
        Thread.setDefaultUncaughtExceptionHandler(new ThreadExceptionHandler());
        SpringApplication.run(EliteIMClientApplication.class, args);
    }


    // 开启一个控制台输入线程
    @Override
    public void run(String... args) throws Exception {
        defaultUserLogin();
        final Thread thread = new Thread(terminalScanner);
        thread.setName("scan-thread");
        thread.start();

    }

    /**
     * 配置文件用户登陆
     */
    private void defaultUserLogin() {
        if (StrUtil.isNotBlank(imClientProperties.getUserId()) &&
                StrUtil.isNotBlank(imClientProperties.getUserName())) {
            loginInnerCommand.process(":login " + imClientProperties.getUserId() + " " + imClientProperties.getUserName());
            log.info("已使用配置文件提供用户[{}]{}进行登陆",imClientProperties.getUserId(),imClientProperties.getUserName());
        } else {
            log.info("配置文件未提供用户id和用户名，请使用:login命令自行登陆~");
        }

    }
}
